package my.socket;

import my.common.Errors;

import java.io.IOException;

/**
 * @author fengbo
 */
public class ServerSocket extends AbstractSocket {

    public ServerSocket(int port) throws IOException {
        this(port, 50);
    }

    public ServerSocket(int port, int backlog) throws IOException {
        super(Native.socket());
        if (port < 0 || port > 0xFFFF) {
            throw new IllegalArgumentException("Port value out of range: " + port);
        }
        bind(port);
        listen(backlog);
    }

    private void bind(int port) throws IOException {
        int res = Native.bind(fileDescriptor, port);
        if (res < 0) {
            throw Errors.newIOException("bind", res);
        }
    }

    private void listen(int backlog) throws IOException {
        int res = Native.listen(fileDescriptor, backlog);
        if (res < 0) {
            throw Errors.newIOException("listen", res);
        }
    }

    public Socket accept() {
        int fd = Native.accept(fileDescriptor);
        return new Socket(fd);
    }

}
